package com.allwees.bs.module.core.req.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.allwees.core.common.util.http.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * RestController拦截器
 *
 * @author yangylsky
 * @since 2019-09-23
 */
@Aspect
@Component
@Slf4j
public class ApiInterceptor {

    @Pointcut("@within(com.allwees.bs.module.core.annotation.PrintLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = StopWatch.createStarted();
        Signature signature = joinPoint.getSignature();
        String method = signature.getDeclaringType().getSimpleName() + "." + signature.getName();
        Object[] params = joinPoint.getArgs();
        StringBuilder builder = new StringBuilder("===> ").append(method).append(",");
        builder.append(",context:").append(RequestContext.getContext());
        builder.append(",params:").append(JSONObject.toJSONString(params));
        log.info(builder.toString());
        Object retObj = joinPoint.proceed();
        stopWatch.stop();
        log.info("<=== {},time spent:{}，result:{}", method, stopWatch.getTime(TimeUnit.MILLISECONDS), JSONObject.toJSONString(retObj));
        return retObj;
    }

}
